<?php
header('Content-Type: application/json; charset=utf-8');

// 引入数据库配置
$dbConfig = include('db_config.php');

// 获取分页参数
$page = $_GET['page'] ?? 1;
$per_page = $_GET['per_page'] ?? 10;

// 计算偏移量
$offset = ($page - 1) * $per_page;

// 创建数据库连接
try {
    $dsn = "mysql:host=" . $dbConfig['host'] . ";dbname=" . $dbConfig['dbname'] . ";charset=" . $dbConfig['charset'];
    $pdo = new PDO($dsn, $dbConfig['username'], $dbConfig['password']);
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

    // 查询视频总数
    $totalCountStmt = $pdo->query("SELECT COUNT(*) FROM mi_videos");
    $total_count = $totalCountStmt->fetchColumn();

    // 查询分页视频信息
    $selectVideosStmt = $pdo->prepare("SELECT * FROM mi_videos LIMIT :limit OFFSET :offset");
    $selectVideosStmt->bindParam(':limit', $per_page, PDO::PARAM_INT);
    $selectVideosStmt->bindParam(':offset', $offset, PDO::PARAM_INT);
    $selectVideosStmt->execute();
    $videos = $selectVideosStmt->fetchAll(PDO::FETCH_ASSOC);

    if (!empty($videos)) {
        // 返回分页视频信息
        $result = [
            'status' => 'success',
            'message' => '获取视频信息成功',
            'current_page' => $page,
            'per_page' => $per_page,
            'total_count' => $total_count,
            'total_pages' => ceil($total_count / $per_page),
            'videos' => $videos
        ];
    } else {
        // 没有视频信息
        $result = [
            'status' => 'error',
            'message' => '没有视频信息'
        ];
    }

    echo json_encode($result, JSON_UNESCAPED_UNICODE);

} catch (PDOException $e) {
    // 数据库操作失败
    $result = [
        'status' => 'error',
        'message' => '数据库操作失败：' . $e->getMessage()
    ];
    echo json_encode($result, JSON_UNESCAPED_UNICODE);
}
?>